package org.glutenberg.dao;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;

import org.glutenberg.Handbook;
import org.glutenberg.util.FileConnectionStreamSource;
import org.glutenberg.util.RandomAccessStreamReader;

public class HandbookDAO {
	
	private FileConnection fc;
	private AlphabeticIndex alphabeticIndex;
	private ReverseIndex reverseIndex;
	private RandomAccessStreamReader reader;
	
	private static String SOURCE_ENCODING = "iso-8859-1";
	
	public HandbookDAO() throws IOException{
		String url = System.getProperty("fileconn.dir.memorycard");
		if(url!=null){
			try{
				this.fc = (FileConnection)Connector.open(url + "prontuario.txt", Connector.READ);
			} catch(IOException e){
				this.fc = this.findHandbook();
				if(this.fc==null) throw new IOException("url: Impossibile trovare prontuario.txt");
			}
		} else {
			this.fc = this.findHandbook();
			if(this.fc==null) throw new IOException("no url: Impossibile trovare prontuario.txt");
		}
		this.reader = new RandomAccessStreamReader(new FileConnectionStreamSource(this.fc), SOURCE_ENCODING);
		Handbook.printUsedMemory();
		this.alphabeticIndex = new AlphabeticIndex(reader);
		Handbook.printUsedMemory();
		this.reverseIndex = new ReverseIndex(reader, this.alphabeticIndex);
	}
	
	private FileConnection findHandbook() throws IOException {
		Enumeration drives = FileSystemRegistry.listRoots();
		String prefix = "file://";
		FileConnection fc = null;
		while(drives.hasMoreElements()){
			String drive = (String)drives.nextElement();
			if(drive.charAt(0)=='/') drive = drive.substring(1);
			if(drive.charAt(drive.length()-1)=='/') drive = drive.substring(0,drive.length()-1);
			fc = (FileConnection)Connector.open(prefix + "/" + drive + "/prontuario.txt", Connector.READ);
			if(fc.exists()) return fc;
		}
		return null;
	}
	
	public ProductReader search(Vector keywords, boolean prepareWords) throws UnsupportedEncodingException, IOException{
		Handbook.printUsedMemory();
		Vector indexes = this.reverseIndex.getProductIndexes(keywords, prepareWords);
		return new ProductReader(this.reverseIndex, this.reader, indexes);
	}

	public ProductReader search(Vector keywords) throws UnsupportedEncodingException, IOException{
		return this.search(keywords, true);
	}
	
	public ProductReader search(String keyword) throws UnsupportedEncodingException, IOException{
		Vector keywords = new Vector();
		keywords.addElement(keyword);
		return this.search(keywords, true);
	}	
}
